<template>
    <!--<div v-show="!vis">-->
    <div>
        <el-form label-width="100px">
            <el-form-item label="SPU名称">
                <el-input v-model="spuInfo.spuName" placeholder="SPU名称"></el-input>
            </el-form-item>

            <el-form-item label="品牌">
                <el-select v-model="spuInfo.tmId" placeholder="请选择品牌">
                    <el-option :value="trademark.id" :label="trademark.tmName" :key="trademark.id"
                               v-for="trademark in trademarks"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="SPU描述">
                <el-input v-model="spuInfo.description" type="textarea" placeholder="SPU描述" rows="4"></el-input>
            </el-form-item>

            <el-form-item label="SPU图片">
                <!--action:上传图片的地址,file-list:显示图片的列表(图片列表需要满足一定的数据格式)-->
                <el-upload v-if="spuInfo.spuImageList" :action="`${$BASE_API}/admin/product/fileUpload`"
                           :file-list="spuInfo.spuImageList" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                           list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-form-item>

            <el-form-item label="销售属性">
                <el-select v-model="attr_Id_Name" :placeholder="unUsedPlaceholder" style="margin-right: 5px;">
                    <el-option :label="unUsedSaleAttr.name" :value="`${unUsedSaleAttr.id}-${unUsedSaleAttr.name}`"
                               v-for="unUsedSaleAttr in unUsedSaleAttrList" :key="unUsedSaleAttr.id"></el-option>
                </el-select>

                <el-button :disabled="!attr_Id_Name" @click="addAttr" type="primary" icon="el-icon-plus">添加销售属性</el-button>

                <el-table style="margin-top: 20px;" border :data="spuInfo.spuSaleAttrList">
                    <el-table-column type="index" align="center" width="80px" label="序号"></el-table-column>

                    <el-table-column label="属性名" prop="saleAttrName"></el-table-column>

                    <el-table-column label="属性值名称列表">
                        <template slot-scope="{row,$index}">
                            <el-tag :key="spuSaleAttrValue.id" v-for="(spuSaleAttrValue,index) in row.spuSaleAttrValueList"
                                    closable :disable-transitions="false"
                                    @close="handleClose(row,index)">{{spuSaleAttrValue.saleAttrValueName}}</el-tag>

                            <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue"
                                    :ref="`saveTagInput${$index}`" size="small" @keyup.enter.native="$event.target.blur"
                                      @blur="handleInputConfirm(row)"></el-input>

                            <el-button v-else class="button-new-tag" size="small" @click="showInput(row,$index)">新增</el-button>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作">
                        <template slot-scope="{row,$index}">
                            <HintButton @click="spuInfo.spuSaleAttrList.splice($index,1)" type="danger"
                                        icon="el-icon-delete" size="mini" title="删除"></HintButton>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
        </el-form>

        <el-button type="primary" icon="el-icon-plus" @click="save" :loading="loading">保存</el-button>
        <el-button @click="cancel">取消</el-button>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                dialogVisible: false,
                dialogImageUrl: '',
                trademarks: [],     // 品牌列表
                baseSaleAttrList: [],   // 属性列表
                spuInfo: {
                    spuName: '',
                    description: '',
                    category3Id: '',
                    tmId: '',
                    spuSaleAttrList: [],    // 和编辑模式 显示模式切换相关的数据 都应该在spuSaleAttrList的每一项中
                    spuImageList: [],
                },
                spuId: '',
                // 销售属性的id和名字
                attr_Id_Name: '',
                loading: false,
            }
        },
        computed: {
            unUsedSaleAttrList() {
                let {baseSaleAttrList,spuInfo:{spuSaleAttrList}} = this;

                return baseSaleAttrList.filter((baseSaleAttr) => {
                    return !spuSaleAttrList.some((spuSaleAttr) => {
                        return baseSaleAttr.id === spuSaleAttr.baseSaleAttrId
                    })
                })
            },

            unUsedPlaceholder() {
                return this.unUsedSaleAttrList.length === 0 ? '没有了': `还剩${this.unUsedSaleAttrList.length}未选择`;
            }
        },
        methods: {
            reset() {
                this.dialogVisible=false;
                this.dialogImageUrl= '';

                this.trademarks=[];    // 品牌列表
                this.baseSaleAttrList= [];   // 属性列表
                this.spuInfo= {
                    spuName: '',
                    description: '',
                    category3Id: '',
                    tmId: '',
                    spuSaleAttrList: [],    // 和编辑模式 显示模式切换相关的数据 都应该在spuSaleAttrList的每一项中
                    spuImageList: [],
                };
                this.spuId= '';
                // 销售属性的id和名字
                this.attr_Id_Name= '';

                this.loading= false;
            },

            handleRemove(file, fileList) {
                this.spuInfo.spuImageList = fileList;
            },
            //上传头像成功之后调用的回调
            handleAvatarSuccess(res, file,fileList) {
                // res: 图片上传成功之后返回的信息(上传接口返回的)
                // file : 你上传成功的那张图片的信息
                // fileList : 当前完成操作后 界面上剩下的图片信息数组
                this.spuInfo.spuImageList = fileList;
            },
            //上传头像之前的钩子 如果返回true则允许调用action指定的接口进行上传操作
            beforeAvatarUpload(file) {
                console.log(file);
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024  < 50;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 50kb!');
                }

                //最终能放行 图片类型必须是jpg 大小必须小于50kb
                return isJPG && isLt2M;
            },
            //on-preview: 点击图片的钩子
            handlePictureCardPreview(file) {
                //file :点击的那张图的信息
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            // 修改父组件中的showList
            cancel() {
                // 使用$parent修改父组件数据
                // this.$parent.$parent.showList = true;
                // this.$emit('update:vis',true);

                this.$parent.$parent.showListFn();

                this.$parent.$parent.changeCs();
            },

            // el-tag
            handleClose(row,index) {
                row.spuSaleAttrValueList.splice(index,1);
            },

            // 显示模式->编辑模式
            showInput(row,index) {
                if(row.hasOwnProperty('inputVisible')) {
                    row.inputVisible = true;
                }else {
                    this.$set(row,'inputVisible',true);
                }

                this.$nextTick(() => {
                    this.$refs[`saveTagInput${index}`].focus();
                });
            },

            handleInputConfirm(row) {
                const attr = {
                    baseSaleAttrId: row.baseSaleAttrId,
                    saleAttrValueName: row.inputValue,
                };

                row.spuSaleAttrValueList.push(attr);

                row.inputValue = '';
                row.inputVisible = false;
            },

            // 初始化品牌相关数据
            async initUpdateData(spuId) {
                this.spuId = spuId;

                // 获取所有品牌列表
                const {code:trademarkCode,data:trademark} = await this.$API.trademark.getAllTradeMark();
                if(trademarkCode === 200) {
                    this.trademarks = trademark;
                }

                // 获取销售属性列表
                const {code:saleAttrListCode,data:saleAttrListList} = await this.$API.spu.getBaseSaleAttrList();
                if(saleAttrListCode === 200) {
                    this.baseSaleAttrList = saleAttrListList;
                }

                // 获取完整的sup信息
                const {code:spuInfoCode,data:spuInfo} = await this.$API.spu.getspuInfoById(this.spuId);
                if(spuInfoCode === 200) {
                    this.spuInfo = spuInfo;
                }

                // 获取spu图片信息
                const {code:spuImageCode,data:spuImageList} = await this.$API.spu.getSpuImageList(this.spuId);
                if(spuImageCode === 200) {
                    this.spuInfo.spuImageList = spuImageList.map((spuImage) => {
                        return {
                            id: spuImage.id,
                            name: spuImage.imgName,
                            url: spuImage.imgUrl,
                            supId: spuImage.spuId,
                            status: spuImage.status,
                            uid: spuImage.uid,
                        }
                    });
                }
            },

            async initAddData(category3Id) {
                // 新增由于之前重置了data中的数据,没有category3Id,因此需要手动添加上
                this.spuInfo.category3Id = category3Id;

                // 获取所有品牌列表
                const {code:trademarkCode,data:trademark} = await this.$API.trademark.getAllTradeMark();
                if(trademarkCode === 200) {
                    this.trademarks = trademark;
                }

                // 获取销售属性列表
                const {code:saleAttrListCode,data:saleAttrListList} = await this.$API.spu.getBaseSaleAttrList();
                if(saleAttrListCode === 200) {
                    this.baseSaleAttrList = saleAttrListList;
                }

            },

            // 添加销售属性
            addAttr() {
                const [baseSaleAttrId,saleAttrName] = this.attr_Id_Name.split('-');
                let attr = {
                    baseSaleAttrId: +baseSaleAttrId,
                    saleAttrName: saleAttrName,
                    spuSaleAttrValueList: [],
                };

                this.spuInfo.spuSaleAttrList.push(attr);

                this.attr_Id_Name = ''
            },

            // 发送新增或修改请求
            async save() {
                this.spuInfo.spuImageList = this.spuInfo.spuImageList.map((spuIamge) => {
                   return {
                       imgName: spuIamge.name,
                       imgUrl: spuIamge.response ? spuIamge.response.data : spuIamge.url,
                   }
                });
                try{
                    this.loading = true;
                    const {code} = await this.$API.spu.addAndUpdate(this.spuInfo);
                    if(code === 200) {
                        this.$message({
                            message: `${this.spuInfo.id}`?'修改成功':'添加成功',
                            type: 'success'
                        });
                        // 关闭页面
                        this.$parent.$parent.showListFn();
                        // 通知spu重新刷新页面
                        this.$emit('success');
                    }
                }catch (e) {
                    this.$message({
                        message: '请求失败',
                        type: 'error'
                    })
                }finally {
                    this.loading = false;
                }
            }
        },
        // 使用.sync修改父组件数据
        // props: ['vis'],
        name: "spuForm",
    }
</script>

<style>
    .el-tag + .el-tag {
        margin-left: 10px;
    }
    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }
    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }
</style>
